//
//  WKWeb3Module.m
//  WuKongWeb3
//
//  Created by tt on 2023/9/17.
//

#import "WKWeb3Module.h"

@WKModule(WKWeb3Module)
@implementation WKWeb3Module


+(NSString*) gModuleID {
    return @"WuKongWeb3";
}

-(NSString*) moduleId {
    return [[self class] gModuleID];
}


- (void)moduleInit:(WKModuleContext*)context{
    NSLog(@"【WuKongUsernameLogin】模块初始化！");
    
    __weak typeof(self) weakSelf = self;
    [self setMethod:@"contacts.header.laboratory" handler:^id _Nullable(id  _Nonnull param) {
       
        WKContactsHeaderItem *item = [WKContactsHeaderItem initWithSid:@"laboratory" title:LLangW(@"实验室",weakSelf) icon:@"IconLaboratory" moduleID:[weakSelf moduleId] onClick:^{
            [weakSelf onLaboratory];
        }];
        return item;
    } category:WKPOINT_CATEGORY_CONTACTSITEM sort:4000];
}

-(void) onLaboratory {
    __weak typeof(self) weakSelf = self;
    UIAlertController *aertController = [UIAlertController alertControllerWithTitle:LLang(@"输入口令") message:nil preferredStyle:UIAlertControllerStyleAlert];
    __block UITextField *input;
    [aertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        input = textField;
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:LLang(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:LLang(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf onLaboratoryOk:input.text];
    }];
    [aertController addAction:cancelAction];
    [aertController addAction:okAction];
    [WKNavigationManager.shared.topViewController presentViewController:aertController animated:YES completion:nil];
}

-(void) onLaboratoryOk:(NSString*)shortURL {
    UIView *topView = WKNavigationManager.shared.topViewController.view;
    [topView showHUD];
    [WKAPIClient.sharedClient GET:@"web3/laboratory" parameters:@{@"short_url":shortURL}].then(^(NSDictionary *resultDict){
        [topView hideHud];
        NSString *urlStr = resultDict[@"url"];
        if(urlStr && urlStr.length>0) {
            WKWebViewVC *vc = [WKWebViewVC new];
            vc.url = [NSURL URLWithString:urlStr];
            [[WKNavigationManager shared] pushViewController:vc animated:YES];
        }
    }).catch(^(NSError *error){
        [topView switchHUDError:error.domain];
    });
}


@end
